package parser;

import java.io.PrintWriter;

import lexer.Token;

/**
 * Parses and stores a Logo Command into a data structure. Grammar: LEFT (expr),
 * RIGHT (expr) or FORWARD(expr)
 */
public class LogoCommandStatement extends LogoStatement {

	String commandString;
	LogoExpression expression;

	/**
	 * Parses a Command Statement from the current Token in TokenIterator
	 * 
	 * @param TokenIterator
	 * @throws LogoParseException
	 */
	public LogoCommandStatement(TokenIterator it) throws LogoParseException {
		parseTokens(it);
	}

	private void parseTokens(TokenIterator it) throws LogoParseException {
		if (!it.hasNext()) {
			throw new LogoParseException("Unexpectly reached end of program");
		}
		Token command = it.next();
		switch (command.getType()) {
		case FORWARD:
		case LEFT:
		case RIGHT:
		case SETRED:
		case SETGREEN:
		case SETBLUE:
		case SETSTROKEWIDTH:
			commandString = command.getType().toString().toLowerCase();
			break;
		default:
			throw new LogoParseSyntaxException(command, "FORWARD, LEFT, RIGHT");
		}
		expression = LogoExpressionParser.parseExpression(it);
	}

	@Override
	public void resolveIdentifiers(LogoScope scope) throws LogoParseException {
		expression.resolveIdentifiers(scope);
	}

	/**
	 * Examples: "5 left" "LEVEL 1 sub forward"
	 */
	@Override
	public void generatePostScriptCode(PrintWriter stream) {
		expression.generatePostScriptCode(stream);
		stream.println(commandString);
	}
}
